<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="Ivar objc_property_t Protocol解读, Swift, iOS, Python">
    <meta name="description" content="群组欢迎加入群组,闲聊工作&amp;amp;技术&amp;amp;问题等

Ivar声明在objc-private.h文件中我们可以看到Ivar的声明结构:
typedef struct ivar_t *Ivar;
在objc-runtime-new.h中">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Ivar objc_property_t Protocol解读 | waitwalker</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<!--导航-->

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    <!---->
                    <!--<img src="/medias/logo.png" class="logo-img" alt="LOGO">-->
                    <!---->
                    <span class="logo-span">waitwalker</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">waitwalker</div>
        <div class="logo-desc">
            
            Life is measured by thought and action not by time.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/waitwalker" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/waitwalker" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="https://github.com/waitwalker" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/5.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        Ivar objc_property_t Protocol解读
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Runtime/" target="_blank">
                                <span class="chip bg-color">Runtime</span>
                            </a>
                        
                            <a href="/tags/底层/" target="_blank">
                                <span class="chip bg-color">底层</span>
                            </a>
                        
                            <a href="/tags/源码/" target="_blank">
                                <span class="chip bg-color">源码</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                Runtime源码解读
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-15
                </div>

                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><strong>群组</strong><br><strong>欢迎加入群组,闲聊工作&amp;技术&amp;问题等</strong></p>
<p><img src="https://github.com/waitwalker/Resources/blob/master/Flutter/group/flutter_development_0923.JPG?raw=true" width="350" height="480" align="center"></p>
<h3 id="Ivar声明"><a href="#Ivar声明" class="headerlink" title="Ivar声明"></a>Ivar声明</h3><p>在objc-private.h文件中我们可以看到Ivar的声明结构:</p>
<pre><code>typedef struct ivar_t *Ivar;
</code></pre><p>在objc-runtime-new.h中可以找到ivar_t的完整结构声明:</p>
<pre><code>// MARK: - 成员变量结构声明
struct ivar_t {
#if __x86_64__
    // *offset was originally 64-bit on some x86_64 platforms.
    // We read and write only 32 bits of it.
    // Some metadata provides all 64 bits. This is harmless for unsigned
    // little-endian values.
    // Some code uses all 64 bits. class_addIvar() over-allocates the
    // offset for their benefit.
#endif
    int32_t *offset;
    const char *name;//成员变量名称
    const char *type;//成员变量类型
    // alignment is sometimes -1; use alignment() instead
    uint32_t alignment_raw;
    uint32_t size;

    uint32_t alignment() const {
        if (alignment_raw == ~(uint32_t)0) return 1U &lt;&lt; WORD_SHIFT;
        return 1 &lt;&lt; alignment_raw;
    }
};
</code></pre><h3 id="Ivar相关接口"><a href="#Ivar相关接口" class="headerlink" title="Ivar相关接口"></a>Ivar相关接口</h3><p>在runtime.h文件:</p>
<h4 id="修改一个类的成员变量的值"><a href="#修改一个类的成员变量的值" class="headerlink" title="修改一个类的成员变量的值"></a>修改一个类的成员变量的值</h4><pre><code>// MARK: - 修改一个类的成员变量的值
/**
 * Changes the value of an instance variable of a class instance.
 *
 * @param obj A pointer to an instance of a class. Pass the object containing
 *  the instance variable whose value you wish to modify.
 * @param name A C string. Pass the name of the instance variable whose value you wish to modify.
 * @param value The new value for the instance variable.
 *
 * @return A pointer to the \c Ivar data structure that defines the type and
 *  name of the instance variable specified by \e name.
 *
 * @note Instance variables with known memory management (such as ARC strong and weak)
 *  use that memory management. Instance variables with unknown memory management
 *  are assigned as if they were unsafe_unretained.
 */
OBJC_EXPORT Ivar _Nullable
object_setInstanceVariable(id _Nullable obj, const char * _Nonnull name,
                           void * _Nullable value)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0)
    OBJC_ARC_UNAVAILABLE;
</code></pre><p>其实现在objc-class.mm文件中,其内部调用了一个私有函数:</p>
<pre><code>// 修改一个类的成员变量的值
Ivar object_setInstanceVariable(id obj, const char *name, void *value)
{
    return _object_setInstanceVariable(obj, name, value, false);
}

// 修改一个成员变量的值
static ALWAYS_INLINE
Ivar _object_setInstanceVariable(id obj, const char *name, void *value,
                                 bool assumeStrong)
{
    Ivar ivar = nil;

    if (obj  &amp;&amp;  name  &amp;&amp;  !obj-&gt;isTaggedPointer()) {
        // 首先根据成员变量名称从ivar_list中获取ivar
        if ((ivar = _class_getVariable(obj-&gt;ISA(), name))) {

            // 更新ivar的value
            _object_setIvar(obj, ivar, (id)value, assumeStrong);
        }
    }
    return ivar;
}
</code></pre><p>首先根据成员变量名称从ivar_list中获取ivar:</p>
<pre><code>// MARK: - 根据成员变量名称获取成员变量
/***********************************************************************
* _class_getVariable
* fixme
* Locking: read-locks runtimeLock
**********************************************************************/
Ivar
_class_getVariable(Class cls, const char *name)
{
    mutex_locker_t lock(runtimeLock);

    for ( ; cls; cls = cls-&gt;superclass) {
        ivar_t *ivar = getIvar(cls, name);
        if (ivar) {
            return ivar;
        }
    }

    return nil;
}

// MARK: - 根据成员变量名称获取成员变量
/***********************************************************************
* getIvar
* Look up an ivar by name.
* Locking: runtimeLock must be read- or write-locked by the caller.
**********************************************************************/
static ivar_t *getIvar(Class cls, const char *name)
{
    runtimeLock.assertLocked();

    const ivar_list_t *ivars;
    assert(cls-&gt;isRealized());
    if ((ivars = cls-&gt;data()-&gt;ro-&gt;ivars)) {
        for (auto&amp; ivar : *ivars) {
            if (!ivar.offset) continue;  // anonymous bitfield

            // ivar.name may be nil for anonymous bitfields etc.
            if (ivar.name  &amp;&amp;  0 == strcmp(name, ivar.name)) {
                return &amp;ivar;
            }
        }
    }

    return nil;
}
</code></pre><p>获取到成员变量后,更新ivar的value:</p>
<pre><code>// MARK: - 更新ivar的值
static ALWAYS_INLINE
void _object_setIvar(id obj, Ivar ivar, id value, bool assumeStrong)
{
    if (!obj  ||  !ivar  ||  obj-&gt;isTaggedPointer()) return;

    ptrdiff_t offset;
    objc_ivar_memory_management_t memoryManagement;
    _class_lookUpIvar(obj-&gt;ISA(), ivar, offset, memoryManagement);

    if (memoryManagement == objc_ivar_memoryUnknown) {
        if (assumeStrong) memoryManagement = objc_ivar_memoryStrong;
        else memoryManagement = objc_ivar_memoryUnretained;
    }

    id *location = (id *)((char *)obj + offset);

    switch (memoryManagement) {
    case objc_ivar_memoryWeak:       objc_storeWeak(location, value); break;
    case objc_ivar_memoryStrong:     objc_storeStrong(location, value); break;
    case objc_ivar_memoryUnretained: *location = value; break;
    case objc_ivar_memoryUnknown:    _objc_fatal(&quot;impossible&quot;);
    }
}
</code></pre><p>更新值的规则主要根据ivar的内存管理语义:</p>
<pre><code>/*
  &quot;Unknown&quot; includes non-object ivars and non-ARC non-__weak ivars
  &quot;Strong&quot; includes ARC __strong ivars
  &quot;Weak&quot; includes ARC and new MRC __weak ivars
  &quot;Unretained&quot; includes ARC __unsafe_unretained and old GC+MRC __weak ivars
*/
typedef enum {
    objc_ivar_memoryUnknown,     // unknown / unknown
    objc_ivar_memoryStrong,      // direct access / objc_storeStrong
    objc_ivar_memoryWeak,        // objc_loadWeak[Retained] / objc_storeWeak
    objc_ivar_memoryUnretained   // direct access / direct access
} objc_ivar_memory_management_t;
</code></pre><p>strong修饰的直接调用objc_storeStrong,weak调用objc_storeWeak,unretained修饰的直接赋值.这个在以后内存管理中细说.</p>
<h4 id="修改一个strong修饰的ivar的值"><a href="#修改一个strong修饰的ivar的值" class="headerlink" title="修改一个strong修饰的ivar的值"></a>修改一个strong修饰的ivar的值</h4><pre><code>// MARK: - 修改一个strong修饰的ivar的值
/**
 * Changes the value of an instance variable of a class instance.
 *
 * @param obj A pointer to an instance of a class. Pass the object containing
 *  the instance variable whose value you wish to modify.
 * @param name A C string. Pass the name of the instance variable whose value you wish to modify.
 * @param value The new value for the instance variable.
 *
 * @return A pointer to the \c Ivar data structure that defines the type and
 *  name of the instance variable specified by \e name.
 *
 * @note Instance variables with known memory management (such as ARC strong and weak)
 *  use that memory management. Instance variables with unknown memory management
 *  are assigned as if they were strong.
 */
OBJC_EXPORT Ivar _Nullable
object_setInstanceVariableWithStrongDefault(id _Nullable obj,
                                            const char * _Nonnull name,
                                            void * _Nullable value)
    OBJC_AVAILABLE(10.12, 10.0, 10.0, 3.0, 2.0)
    OBJC_ARC_UNAVAILABLE;
</code></pre><p>其过程与上一个类似.</p>
<h4 id="获取一个类的实例的成员变量-的值"><a href="#获取一个类的实例的成员变量-的值" class="headerlink" title="获取一个类的实例的成员变量(的值)"></a>获取一个类的实例的成员变量(的值)</h4><pre><code>// MARK: - 获取一个类的实例的成员变量(的值)
/**
 * Obtains the value of an instance variable of a class instance.
 *
 * @param obj A pointer to an instance of a class. Pass the object containing
 *  the instance variable whose value you wish to obtain.
 * @param name A C string. Pass the name of the instance variable whose value you wish to obtain.
 * @param outValue On return, contains a pointer to the value of the instance variable.
 *
 * @return A pointer to the \c Ivar data structure that defines the type and name of
 *  the instance variable specified by \e name.
 */
OBJC_EXPORT Ivar _Nullable
object_getInstanceVariable(id _Nullable obj, const char * _Nonnull name,
                           void * _Nullable * _Nullable outValue)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0)
    OBJC_ARC_UNAVAILABLE;

// 获取实例的成员变量
Ivar object_getInstanceVariable(id obj, const char *name, void **value)
{
    if (obj  &amp;&amp;  name  &amp;&amp;  !obj-&gt;isTaggedPointer()) {
        Ivar ivar;
        if ((ivar = class_getInstanceVariable(obj-&gt;ISA(), name))) {
            if (value) *value = (void *)object_getIvar(obj, ivar);
            return ivar;
        }
    }
    if (value) *value = nil;
    return nil;
}
</code></pre><h4 id="获取一个类所有成员变量的size"><a href="#获取一个类所有成员变量的size" class="headerlink" title="获取一个类所有成员变量的size"></a>获取一个类所有成员变量的size</h4><pre><code>// MARK: - 获取一个类所有成员变量的size
/**
 * Returns the size of instances of a class.
 *
 * @param cls A class object.
 *
 * @return The size in bytes of instances of the class \e cls, or \c 0 if \e cls is \c Nil.
 */
OBJC_EXPORT size_t
class_getInstanceSize(Class _Nullable cls)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取一个类所有成员变量的size
size_t class_getInstanceSize(Class cls)
{
    if (!cls) return 0;
    return cls-&gt;alignedInstanceSize();
}

// Class&#39;s ivar size rounded up to a pointer-size boundary.
    uint32_t alignedInstanceSize() {
        return word_align(unalignedInstanceSize());
    }

 // May be unaligned depending on class&#39;s ivars.
    uint32_t unalignedInstanceSize() {
        assert(isRealized());
        // 返回一个类中所有成员变量的size
        return data()-&gt;ro-&gt;instanceSize;
    }
</code></pre><p>这里也印证了我们之前文章所说的一个类的成员变量在编译后内存布局已经固定了,其获取大小是从data()-&gt;ro-&gt;instanceSize来.</p>
<h4 id="根据成员变量名称获取某个类中的成员变量-objc-getInstanceVariable中调用的就是此函数"><a href="#根据成员变量名称获取某个类中的成员变量-objc-getInstanceVariable中调用的就是此函数" class="headerlink" title="根据成员变量名称获取某个类中的成员变量(objc_getInstanceVariable中调用的就是此函数)"></a>根据成员变量名称获取某个类中的成员变量(objc_getInstanceVariable中调用的就是此函数)</h4><pre><code>// MARK: - 根据成员变量名称获取某个类中的成员变量(objc_getInstanceVariable中调用的就是此函数)
/**
 * Returns the \c Ivar for a specified instance variable of a given class.
 *
 * @param cls The class whose instance variable you wish to obtain.
 * @param name The name of the instance variable definition to obtain.
 *
 * @return A pointer to an \c Ivar data structure containing information about
 *  the instance variable specified by \e name.
 */
OBJC_EXPORT Ivar _Nullable
class_getInstanceVariable(Class _Nullable cls, const char * _Nonnull name)
    OBJC_AVAILABLE(10.0, 2.0, 9.0, 1.0, 2.0);

// MARK: - 根据名称获取一个类中的成员变量
/***********************************************************************
* class_getInstanceVariable.  Return the named instance variable.
**********************************************************************/
Ivar class_getInstanceVariable(Class cls, const char *name)
{
    if (!cls  ||  !name) return nil;

    return _class_getVariable(cls, name);
}
</code></pre><h4 id="通过名称获取类成员变量"><a href="#通过名称获取类成员变量" class="headerlink" title="通过名称获取类成员变量"></a>通过名称获取类成员变量</h4><pre><code>// MARK: - 通过名称获取类成员变量
/**
 * Returns the Ivar for a specified class variable of a given class.
 *
 * @param cls The class definition whose class variable you wish to obtain.
 * @param name The name of the class variable definition to obtain.
 *
 * @return A pointer to an \c Ivar data structure containing information about the class variable specified by \e name.
 */
OBJC_EXPORT Ivar _Nullable
class_getClassVariable(Class _Nullable cls, const char * _Nonnull name)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取类中的类成员变量
/***********************************************************************
* class_getClassVariable.  Return the named class variable.
**********************************************************************/
Ivar class_getClassVariable(Class cls, const char *name)
{
    if (!cls) return nil;

    return class_getInstanceVariable(cls-&gt;ISA(), name);
}
</code></pre><h4 id="获取一个类的所有成员变量"><a href="#获取一个类的所有成员变量" class="headerlink" title="获取一个类的所有成员变量"></a>获取一个类的所有成员变量</h4><pre><code>// MARK: - 获取一个类的所有成员变量
/**
 * Describes the instance variables declared by a class.
 *
 * @param cls The class to inspect.
 * @param outCount On return, contains the length of the returned array.
 *  If outCount is NULL, the length is not returned.
 *
 * @return An array of pointers of type Ivar describing the instance variables declared by the class.
 *  Any instance variables declared by superclasses are not included. The array contains *outCount
 *  pointers followed by a NULL terminator. You must free the array with free().
 *
 *  If the class declares no instance variables, or cls is Nil, NULL is returned and *outCount is 0.
 */
OBJC_EXPORT Ivar _Nonnull * _Nullable
class_copyIvarList(Class _Nullable cls, unsigned int * _Nullable outCount)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取一个类的所有成员变量
/***********************************************************************
* class_copyIvarList
* fixme
* Locking: read-locks runtimeLock
**********************************************************************/
Ivar *
class_copyIvarList(Class cls, unsigned int *outCount)
{
    const ivar_list_t *ivars;
    Ivar *result = nil;
    unsigned int count = 0;

    if (!cls) {
        if (outCount) *outCount = 0;
        return nil;
    }

    mutex_locker_t lock(runtimeLock);

    assert(cls-&gt;isRealized());

    if ((ivars = cls-&gt;data()-&gt;ro-&gt;ivars)  &amp;&amp;  ivars-&gt;count) {
        result = (Ivar *)malloc((ivars-&gt;count+1) * sizeof(Ivar));

        for (auto&amp; ivar : *ivars) {
            if (!ivar.offset) continue;  // anonymous bitfield
            result[count++] = &amp;ivar;
        }
        result[count] = nil;
    }

    if (outCount) *outCount = count;
    return result;
}
</code></pre><p>其获取主要来自:cls-&gt;data()-&gt;ro-&gt;ivars.</p>
<h4 id="给一个类添加成员变量-必须在调用objc-allocateClassPair之后在objc-registerClassPair之前"><a href="#给一个类添加成员变量-必须在调用objc-allocateClassPair之后在objc-registerClassPair之前" class="headerlink" title="给一个类添加成员变量:必须在调用objc_allocateClassPair之后在objc_registerClassPair之前"></a>给一个类添加成员变量:必须在调用objc_allocateClassPair之后在objc_registerClassPair之前</h4><pre><code>// MARK: - 给一个类添加成员变量:必须在调用objc_allocateClassPair之后在objc_registerClassPair之前
/**
 * Adds a new instance variable to a class.
 *
 * @return YES if the instance variable was added successfully, otherwise NO
 *         (for example, the class already contains an instance variable with that name).
 *
 * @note This function may only be called after objc_allocateClassPair and before objc_registerClassPair.
 *       Adding an instance variable to an existing class is not supported.
 * @note The class must not be a metaclass. Adding an instance variable to a metaclass is not supported.
 * @note The instance variable&#39;s minimum alignment in bytes is 1&lt;&lt;align. The minimum alignment of an instance
 *       variable depends on the ivar&#39;s type and the machine architecture.
 *       For variables of any pointer type, pass log2(sizeof(pointer_type)).
 */
OBJC_EXPORT BOOL
class_addIvar(Class _Nullable cls, const char * _Nonnull name, size_t size,
              uint8_t alignment, const char * _Nullable types)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 给一个类添加成员变量
/***********************************************************************
* class_addIvar
* Adds an ivar to a class.
* Locking: acquires runtimeLock
**********************************************************************/
BOOL
class_addIvar(Class cls, const char *name, size_t size,
              uint8_t alignment, const char *type)
{
    if (!cls) return NO;

    if (!type) type = &quot;&quot;;
    if (name  &amp;&amp;  0 == strcmp(name, &quot;&quot;)) name = nil;

    mutex_locker_t lock(runtimeLock);

    checkIsKnownClass(cls);
    assert(cls-&gt;isRealized());

    // No class variables
    if (cls-&gt;isMetaClass()) {
        return NO;
    }

    // Can only add ivars to in-construction classes.
    if (!(cls-&gt;data()-&gt;flags &amp; RW_CONSTRUCTING)) {
        return NO;
    }

    // Check for existing ivar with this name, unless it&#39;s anonymous.
    // Check for too-big ivar.
    // fixme check for superclass ivar too?
    if ((name  &amp;&amp;  getIvar(cls, name))  ||  size &gt; UINT32_MAX) {
        return NO;
    }

    class_ro_t *ro_w = make_ro_writeable(cls-&gt;data());

    // fixme allocate less memory here

    ivar_list_t *oldlist, *newlist;
    if ((oldlist = (ivar_list_t *)cls-&gt;data()-&gt;ro-&gt;ivars)) {
        size_t oldsize = oldlist-&gt;byteSize();
        newlist = (ivar_list_t *)calloc(oldsize + oldlist-&gt;entsize(), 1);
        memcpy(newlist, oldlist, oldsize);
        free(oldlist);
    } else {
        newlist = (ivar_list_t *)calloc(sizeof(ivar_list_t), 1);
        newlist-&gt;entsizeAndFlags = (uint32_t)sizeof(ivar_t);
    }

    uint32_t offset = cls-&gt;unalignedInstanceSize();
    uint32_t alignMask = (1&lt;&lt;alignment)-1;
    offset = (offset + alignMask) &amp; ~alignMask;

    ivar_t&amp; ivar = newlist-&gt;get(newlist-&gt;count++);
#if __x86_64__
    // Deliberately over-allocate the ivar offset variable.
    // Use calloc() to clear all 64 bits. See the note in struct ivar_t.
    ivar.offset = (int32_t *)(int64_t *)calloc(sizeof(int64_t), 1);
#else
    ivar.offset = (int32_t *)malloc(sizeof(int32_t));
#endif
    *ivar.offset = offset;
    ivar.name = name ? strdupIfMutable(name) : nil;
    ivar.type = strdupIfMutable(type);
    ivar.alignment_raw = alignment;
    ivar.size = (uint32_t)size;

    ro_w-&gt;ivars = newlist;
    cls-&gt;setInstanceSize((uint32_t)(offset + size));

    // Ivar layout updated in registerClass.

    return YES;
}
</code></pre><h4 id="获取成员变量名称"><a href="#获取成员变量名称" class="headerlink" title="获取成员变量名称"></a>获取成员变量名称</h4><pre><code>// MARK: - 获取成员变量名称
/* Working with Instance Variables */

/**
 * Returns the name of an instance variable.
 *
 * @param v The instance variable you want to enquire about.
 *
 * @return A C string containing the instance variable&#39;s name.
 */
OBJC_EXPORT const char * _Nullable
ivar_getName(Ivar _Nonnull v)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取成员变量名称
/***********************************************************************
* ivar_getName
* fixme
* Locking: none
**********************************************************************/
const char *
ivar_getName(Ivar ivar)
{
    if (!ivar) return nil;
    return ivar-&gt;name;
}
</code></pre><h4 id="获取成员变量类型"><a href="#获取成员变量类型" class="headerlink" title="获取成员变量类型"></a>获取成员变量类型</h4><pre><code>// MARK: - 获取成员变量类型
/**
 * Returns the type string of an instance variable.
 *
 * @param v The instance variable you want to enquire about.
 *
 * @return A C string containing the instance variable&#39;s type encoding.
 *
 * @note For possible values, see Objective-C Runtime Programming Guide &gt; Type Encodings.
 */
OBJC_EXPORT const char * _Nullable
ivar_getTypeEncoding(Ivar _Nonnull v)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取成员变量名称
/***********************************************************************
* ivar_getTypeEncoding
* fixme
* Locking: none
**********************************************************************/
const char *
ivar_getTypeEncoding(Ivar ivar)
{
    if (!ivar) return nil;
    return ivar-&gt;type;
}
</code></pre><h3 id="property声明"><a href="#property声明" class="headerlink" title="property声明"></a>property声明</h3><pre><code>/// An opaque type that represents an Objective-C declared property.
typedef struct objc_property *objc_property_t;
</code></pre><p>完整声明在objc-runtime-new.h文件中:</p>
<pre><code>// MARK: - 属性声明
struct property_t {
    const char *name;
    const char *attributes;
};
</code></pre><h4 id="根据名称获取一个类的属性"><a href="#根据名称获取一个类的属性" class="headerlink" title="根据名称获取一个类的属性"></a>根据名称获取一个类的属性</h4><pre><code>// MARK: - 根据名称获取一个类的属性
/**
 * Returns a property with a given name of a given class.
 *
 * @param cls The class you want to inspect.
 * @param name The name of the property you want to inspect.
 *
 * @return A pointer of type \c objc_property_t describing the property, or
 *  \c NULL if the class does not declare a property with that name,
 *  or \c NULL if \e cls is \c Nil.
 */
OBJC_EXPORT objc_property_t _Nullable
class_getProperty(Class _Nullable cls, const char * _Nonnull name)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 根据名称获取一个类中的属性
/***********************************************************************
* class_getProperty
* fixme
* Locking: read-locks runtimeLock
**********************************************************************/
objc_property_t class_getProperty(Class cls, const char *name)
{
    if (!cls  ||  !name) return nil;

    mutex_locker_t lock(runtimeLock);

    checkIsKnownClass(cls);

    assert(cls-&gt;isRealized());

    for ( ; cls; cls = cls-&gt;superclass) {
        for (auto&amp; prop : cls-&gt;data()-&gt;properties) {
            if (0 == strcmp(name, prop.name)) {
                return (objc_property_t)&amp;prop;
            }
        }
    }

    return nil;
}
</code></pre><p>先判断cls有没有实现,然后可以看到其获取时从可变class_rw_t的成员变量properties中获得:cls-&gt;data()-&gt;properties.</p>
<h4 id="获取一个类的属性列表"><a href="#获取一个类的属性列表" class="headerlink" title="获取一个类的属性列表"></a>获取一个类的属性列表</h4><pre><code>// MARK: - 获取一个类的属性列表
/**
 * Describes the properties declared by a class.
 *
 * @param cls The class you want to inspect.
 * @param outCount On return, contains the length of the returned array.
 *  If \e outCount is \c NULL, the length is not returned.
 *
 * @return An array of pointers of type \c objc_property_t describing the properties
 *  declared by the class. Any properties declared by superclasses are not included.
 *  The array contains \c *outCount pointers followed by a \c NULL terminator. You must free the array with \c free().
 *
 *  If \e cls declares no properties, or \e cls is \c Nil, returns \c NULL and \c *outCount is \c 0.
 */
OBJC_EXPORT objc_property_t _Nonnull * _Nullable
class_copyPropertyList(Class _Nullable cls, unsigned int * _Nullable outCount)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取一个类的属性列表
/***********************************************************************
* class_copyPropertyList. Returns a heap block containing the
* properties declared in the class, or nil if the class
* declares no properties. Caller must free the block.
* Does not copy any superclass&#39;s properties.
* Locking: read-locks runtimeLock
**********************************************************************/
objc_property_t *
class_copyPropertyList(Class cls, unsigned int *outCount)
{
    if (!cls) {
        if (outCount) *outCount = 0;
        return nil;
    }

    mutex_locker_t lock(runtimeLock);

    checkIsKnownClass(cls);
    assert(cls-&gt;isRealized());

    // 先获取rw
    auto rw = cls-&gt;data();

    property_t **result = nil;
    unsigned int count = rw-&gt;properties.count();
    if (count &gt; 0) {
        result = (property_t **)malloc((count + 1) * sizeof(property_t *));

        count = 0;
        for (auto&amp; prop : rw-&gt;properties) {
            result[count++] = &amp;prop;
        }
        result[count] = nil;
    }

    if (outCount) *outCount = count;
    return (objc_property_t *)result;
}
</code></pre><h4 id="给一个类添加属性"><a href="#给一个类添加属性" class="headerlink" title="给一个类添加属性"></a>给一个类添加属性</h4><pre><code>// MARK: - 给一个类添加属性
/**
 * Adds a property to a class.
 *
 * @param cls The class to modify.
 * @param name The name of the property.
 * @param attributes An array of property attributes.
 * @param attributeCount The number of attributes in \e attributes.
 *
 * @return \c YES if the property was added successfully, otherwise \c NO
 *  (for example, the class already has that property).
 */
OBJC_EXPORT BOOL
class_addProperty(Class _Nullable cls, const char * _Nonnull name,
                  const objc_property_attribute_t * _Nullable attributes,
                  unsigned int attributeCount)
    OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);

// 给一个类添加属性
BOOL
class_addProperty(Class cls, const char *name,
                  const objc_property_attribute_t *attrs, unsigned int n)
{
    return _class_addProperty(cls, name, attrs, n, NO);
}

// 给一个类添加属性
/***********************************************************************
* class_addProperty
* Adds a property to a class.
* Locking: acquires runtimeLock
**********************************************************************/
static bool
_class_addProperty(Class cls, const char *name,
                   const objc_property_attribute_t *attrs, unsigned int count,
                   bool replace)
{
    if (!cls) return NO;
    if (!name) return NO;

    property_t *prop = class_getProperty(cls, name);
    if (prop  &amp;&amp;  !replace) {
        // already exists, refuse to replace
        return NO;
    }
    else if (prop) {
        // replace existing
        mutex_locker_t lock(runtimeLock);
        try_free(prop-&gt;attributes);
        prop-&gt;attributes = copyPropertyAttributeString(attrs, count);
        return YES;
    }
    else {
        mutex_locker_t lock(runtimeLock);

        assert(cls-&gt;isRealized());

        property_list_t *proplist = (property_list_t *)
            malloc(sizeof(*proplist));
        proplist-&gt;count = 1;
        proplist-&gt;entsizeAndFlags = sizeof(proplist-&gt;first);
        proplist-&gt;first.name = strdupIfMutable(name);
        proplist-&gt;first.attributes = copyPropertyAttributeString(attrs, count);

        cls-&gt;data()-&gt;properties.attachLists(&amp;proplist, 1);

        return YES;
    }
}
</code></pre><p>其操作的还是class_rw_t中的成员变量properties;侧面印证class_rw_t是可变的.</p>
<h4 id="更新某个属性值"><a href="#更新某个属性值" class="headerlink" title="更新某个属性值"></a>更新某个属性值</h4><pre><code>// MARK: - 更新某个属性值
/**
 * Replace a property of a class.
 *
 * @param cls The class to modify.
 * @param name The name of the property.
 * @param attributes An array of property attributes.
 * @param attributeCount The number of attributes in \e attributes.
 */
OBJC_EXPORT void
class_replaceProperty(Class _Nullable cls, const char * _Nonnull name,
                      const objc_property_attribute_t * _Nullable attributes,
                      unsigned int attributeCount)
    OBJC_AVAILABLE(10.7, 4.3, 9.0, 1.0, 2.0);

// 更新某个属性
void
class_replaceProperty(Class cls, const char *name,
                      const objc_property_attribute_t *attrs, unsigned int n)
{
    _class_addProperty(cls, name, attrs, n, YES);
}
</code></pre><h4 id="获取属性名称"><a href="#获取属性名称" class="headerlink" title="获取属性名称"></a>获取属性名称</h4><pre><code>// MARK: - 获取属性名称
/* Working with Properties */

/**
 * Returns the name of a property.
 *
 * @param property The property you want to inquire about.
 *
 * @return A C string containing the property&#39;s name.
 */
OBJC_EXPORT const char * _Nonnull
property_getName(objc_property_t _Nonnull property)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取属性名称
const char *property_getName(objc_property_t prop)
{
    return prop-&gt;name;
}
</code></pre><h4 id="获取属性的内存管理语义相关"><a href="#获取属性的内存管理语义相关" class="headerlink" title="获取属性的内存管理语义相关"></a>获取属性的内存管理语义相关</h4><pre><code>// MARK: - 获取属性的内存管理语义相关
/**
 * Returns the attribute string of a property.
 *
 * @param property A property.
 *
 * @return A C string containing the property&#39;s attributes.
 *
 * @note The format of the attribute string is described in Declared Properties in Objective-C Runtime Programming Guide.
 */
OBJC_EXPORT const char * _Nullable
property_getAttributes(objc_property_t _Nonnull property)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取属性的内存管理语义
const char *property_getAttributes(objc_property_t prop)
{
    return prop-&gt;attributes;
}
</code></pre><p>这个获取的到的就是readwrite,stong,atomic等相关.</p>
<h3 id="Protocol的声明"><a href="#Protocol的声明" class="headerlink" title="Protocol的声明"></a>Protocol的声明</h3><pre><code>#ifdef __OBJC__
@class Protocol;
#else
typedef struct objc_object Protocol;
#endif

@implementation Protocol

#if __OBJC2__
// fixme hack - make Protocol a non-lazy class
+ (void) load { }
#endif


- (BOOL) conformsTo: (Protocol *)aProtocolObj
{
    return protocol_conformsToProtocol(self, aProtocolObj);
}

- (struct objc_method_description *) descriptionForInstanceMethod:(SEL)aSel
{
#if !__OBJC2__
    return lookup_protocol_method((struct old_protocol *)self, aSel,
                                  YES/*required*/, YES/*instance*/,
                                  YES/*recursive*/);
#else
    return method_getDescription(protocol_getMethod((struct protocol_t *)self,
                                                     aSel, YES, YES, YES));
#endif
}

- (struct objc_method_description *) descriptionForClassMethod:(SEL)aSel
{
#if !__OBJC2__
    return lookup_protocol_method((struct old_protocol *)self, aSel,
                                  YES/*required*/, NO/*instance*/,
                                  YES/*recursive*/);
#else
    return method_getDescription(protocol_getMethod((struct protocol_t *)self,
                                                    aSel, YES, NO, YES));
#endif
}

- (const char *)name
{
    return protocol_getName(self);
}

- (BOOL)isEqual:other
{
#if __OBJC2__
    // check isKindOf:
    Class cls;
    Class protoClass = objc_getClass(&quot;Protocol&quot;);
    for (cls = object_getClass(other); cls; cls = cls-&gt;superclass) {
        if (cls == protoClass) break;
    }
    if (!cls) return NO;
    // check equality
    return protocol_isEqual(self, other);
#else
    return [other isKindOf:[Protocol class]] &amp;&amp; [self conformsTo: other] &amp;&amp; [other conformsTo: self];
#endif
}

#if __OBJC2__
- (NSUInteger)hash
{
    return 23;
}
#else
- (unsigned)hash
{
    return 23;
}
#endif

@end
</code></pre><p>在runtime.h文件中我们可以看到Protocol被定义为一个类继承自上帝类NSObject.这个类并没有对外暴露什么接口.下面我们看一下protocol_t的完整声明:</p>
<pre><code>// MARK: - 协议的声明结构
struct protocol_t : objc_object {
    const char *mangledName;
    struct protocol_list_t *protocols; //协议列表
    method_list_t *instanceMethods;//实例方法列表
    method_list_t *classMethods;//类方法列表
    method_list_t *optionalInstanceMethods;//可选的实例方法列表
    method_list_t *optionalClassMethods;//可选的类方法列表
    property_list_t *instanceProperties;//属性列表
    uint32_t size;   // sizeof(protocol_t)
    uint32_t flags;
    // Fields below this point are not always present on disk.
    const char **_extendedMethodTypes;
    const char *_demangledName;
    property_list_t *_classProperties;

    const char *demangledName();

    const char *nameForLogging() {
        return demangledName();
    }

    bool isFixedUp() const;
    void setFixedUp();

#   define HAS_FIELD(f) (size &gt;= offsetof(protocol_t, f) + sizeof(f))

    bool hasExtendedMethodTypesField() const {
        return HAS_FIELD(_extendedMethodTypes);
    }
    bool hasDemangledNameField() const {
        return HAS_FIELD(_demangledName);
    }
    bool hasClassPropertiesField() const {
        return HAS_FIELD(_classProperties);
    }

#   undef HAS_FIELD

    const char **extendedMethodTypes() const {
        return hasExtendedMethodTypesField() ? _extendedMethodTypes : nil;
    }

    property_list_t *classProperties() const {
        return hasClassPropertiesField() ? _classProperties : nil;
    }
};
</code></pre><h4 id="给一个类添加协议"><a href="#给一个类添加协议" class="headerlink" title="给一个类添加协议"></a>给一个类添加协议</h4><pre><code>// MARK: - 给一个类添加协议
/**
 * Adds a protocol to a class.
 *
 * @param cls The class to modify.
 * @param protocol The protocol to add to \e cls.
 *
 * @return \c YES if the method was added successfully, otherwise \c NO
 *  (for example, the class already conforms to that protocol).
 */
OBJC_EXPORT BOOL
class_addProtocol(Class _Nullable cls, Protocol * _Nonnull protocol)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 给一个类添加协议
/***********************************************************************
* class_addProtocol
* Adds a protocol to a class.
* Locking: acquires runtimeLock
**********************************************************************/
BOOL class_addProtocol(Class cls, Protocol *protocol_gen)
{
    protocol_t *protocol = newprotocol(protocol_gen);

    if (!cls) return NO;
    if (class_conformsToProtocol(cls, protocol_gen)) return NO;

    mutex_locker_t lock(runtimeLock);

    assert(cls-&gt;isRealized());

    // fixme optimize
    protocol_list_t *protolist = (protocol_list_t *)
        malloc(sizeof(protocol_list_t) + sizeof(protocol_t *));
    protolist-&gt;count = 1;
    protolist-&gt;list[0] = (protocol_ref_t)protocol;

    // 添加到protocols里面
    cls-&gt;data()-&gt;protocols.attachLists(&amp;protolist, 1);

    // fixme metaclass?

    return YES;
}
</code></pre><p>其操作的还是class_rw_t中的成员变量protocols;侧面印证class_rw_t是可变的.</p>
<h4 id="根据名称获取一个协议"><a href="#根据名称获取一个协议" class="headerlink" title="根据名称获取一个协议"></a>根据名称获取一个协议</h4><pre><code>// MARK: - 根据名称获取一个协议
/* Working with Protocols */

/**
 * Returns a specified protocol.
 *
 * @param name The name of a protocol.
 *
 * @return The protocol named \e name, or \c NULL if no protocol named \e name could be found.
 *
 * @note This function acquires the runtime lock.
 */
OBJC_EXPORT Protocol * _Nullable
objc_getProtocol(const char * _Nonnull name)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取协议
/***********************************************************************
* objc_getProtocol
* Get a protocol by name, or return nil
* Locking: read-locks runtimeLock
**********************************************************************/
Protocol *objc_getProtocol(const char *name)
{
    mutex_locker_t lock(runtimeLock);
    return getProtocol(name);
}
</code></pre><h4 id="获取运行时所有的协议列表"><a href="#获取运行时所有的协议列表" class="headerlink" title="获取运行时所有的协议列表"></a>获取运行时所有的协议列表</h4><pre><code>// MARK: - 获取运行时所有的协议列表
/**
 * Returns an array of all the protocols known to the runtime.
 *
 * @param outCount Upon return, contains the number of protocols in the returned array.
 *
 * @return A C array of all the protocols known to the runtime. The array contains \c *outCount
 *  pointers followed by a \c NULL terminator. You must free the list with \c free().
 *
 * @note This function acquires the runtime lock.
 */
OBJC_EXPORT Protocol * __unsafe_unretained _Nonnull * _Nullable
objc_copyProtocolList(unsigned int * _Nullable outCount)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取运行时所有的协议列表
/***********************************************************************
* objc_copyProtocolList
* Returns pointers to all protocols.
* Locking: read-locks runtimeLock
**********************************************************************/
Protocol * __unsafe_unretained *
objc_copyProtocolList(unsigned int *outCount)
{
    mutex_locker_t lock(runtimeLock);

    NXMapTable *protocol_map = protocols();

    unsigned int count = NXCountMapTable(protocol_map);
    if (count == 0) {
        if (outCount) *outCount = 0;
        return nil;
    }

    Protocol **result = (Protocol **)malloc((count+1) * sizeof(Protocol*));

    unsigned int i = 0;
    Protocol *proto;
    const char *name;
    NXMapState state = NXInitMapState(protocol_map);
    while (NXNextMapState(protocol_map, &amp;state,
                          (const void **)&amp;name, (const void **)&amp;proto))
    {
        result[i++] = proto;
    }

    result[i++] = nil;
    assert(i == count+1);

    if (outCount) *outCount = count;
    return result;
}
</code></pre><h4 id="获取某个协议中的某个属性"><a href="#获取某个协议中的某个属性" class="headerlink" title="获取某个协议中的某个属性"></a>获取某个协议中的某个属性</h4><pre><code>// MARK: - 获取某个协议中的某个属性
/**
 * Returns the specified property of a given protocol.
 *
 * @param proto A protocol.
 * @param name The name of a property.
 * @param isRequiredProperty \c YES searches for a required property, \c NO searches for an optional property.
 * @param isInstanceProperty \c YES searches for an instance property, \c NO searches for a class property.
 *
 * @return The property specified by \e name, \e isRequiredProperty, and \e isInstanceProperty for \e proto,
 *  or \c NULL if none of \e proto&#39;s properties meets the specification.
 */
OBJC_EXPORT objc_property_t _Nullable
protocol_getProperty(Protocol * _Nonnull proto,
                     const char * _Nonnull name,
                     BOOL isRequiredProperty, BOOL isInstanceProperty)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取协议中的某个属性
objc_property_t protocol_getProperty(Protocol *p, const char *name,
                              BOOL isRequiredProperty, BOOL isInstanceProperty)
{
    if (!p  ||  !name) return nil;

    mutex_locker_t lock(runtimeLock);
    return (objc_property_t)
        protocol_getProperty_nolock(newprotocol(p), name,
                                    isRequiredProperty, isInstanceProperty);
}
</code></pre><h4 id="获取协议的属性列表"><a href="#获取协议的属性列表" class="headerlink" title="获取协议的属性列表"></a>获取协议的属性列表</h4><pre><code>// MARK: - 获取协议的属性列表
/**
 * Returns an array of the required instance properties declared by a protocol.
 *
 * @note Identical to
 * \code
 * protocol_copyPropertyList2(proto, outCount, YES, YES);
 * \endcode
 */
OBJC_EXPORT objc_property_t _Nonnull * _Nullable
protocol_copyPropertyList(Protocol * _Nonnull proto,
                          unsigned int * _Nullable outCount)
    OBJC_AVAILABLE(10.5, 2.0, 9.0, 1.0, 2.0);

// 获取协议属性列表
objc_property_t *
protocol_copyPropertyList(Protocol *proto, unsigned int *outCount)
{
    return protocol_copyPropertyList2(proto, outCount,
                                      YES/*required*/, YES/*instance*/);
}

// 获取协议属性列表
objc_property_t *
protocol_copyPropertyList2(Protocol *proto, unsigned int *outCount,
                           BOOL isRequiredProperty, BOOL isInstanceProperty)
{
    if (!proto  ||  !isRequiredProperty) {
        // Optional properties are not currently supported.
        if (outCount) *outCount = 0;
        return nil;
    }

    mutex_locker_t lock(runtimeLock);

    property_list_t *plist = isInstanceProperty
        ? newprotocol(proto)-&gt;instanceProperties
        : newprotocol(proto)-&gt;classProperties();
    return (objc_property_t *)copyPropertyList(plist, outCount);
}
</code></pre><h3 id="编译后源码库"><a href="#编译后源码库" class="headerlink" title="编译后源码库"></a>编译后源码库</h3><p><strong>编译后的源码放在<a href="https://github.com/waitwalker/Runtime" target="_blank" rel="noopener">Github</a>, 如果对你有帮助,请给一个star吧!</strong></p>
<h3 id="博客地址-amp-相关文章"><a href="#博客地址-amp-相关文章" class="headerlink" title="博客地址&amp;相关文章"></a>博客地址&amp;相关文章</h3><p><strong>博客地址:</strong> <a href="https://waitwalker.github.io/">https://waitwalker.github.io/</a></p>
<p>系列文章:</p>
<p><a href="https://waitwalker.github.io/2019/04/08/Runtime%E6%BA%90%E7%A0%81%E7%BC%96%E8%AF%91/">1. Runtime源码编译</a></p>
<p><a href="https://waitwalker.github.io/2019/04/10/objc-object%E8%A7%A3%E8%AF%BB/">2. objc_object解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/12/Method%E8%A7%A3%E8%AF%BB/">3. Method解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Class%E8%A7%A3%E8%AF%BB/">4. Class解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Ivar-objc-property-t-Protocol%E8%A7%A3%E8%AF%BB/">5. Ivar objc_property_t Protocol解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/18/Block%E8%A7%A3%E8%AF%BB/">6. Block解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/22/Retain-Release解读/" target="_blank" rel="noopener">7. Retain&amp;Release解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/23/Autorelease解读/" target="_blank" rel="noopener">8. Autorelease解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/24/Weak解读/" target="_blank" rel="noopener">9. Weak解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/25/msgSend-解读/" target="_blank" rel="noopener">10. msgSend()解读</a></p>

            </div>
            <hr>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            <div class="reprint">
                <p>
                    <span class="reprint-tip">
                        <i class="fa fa-exclamation-circle"></i>&nbsp;&nbsp;转载请注明:
                    </span>
                    <a href="https://waitwalker.github.io" class="b-link-green">waitwalker</a>
                    <i class="fa fa-angle-right fa-lg fa-fw text-color"></i>
                    <a href="/2019/04/15/Ivar-objc-property-t-Protocol解读/" class="b-link-green">Ivar objc_property_t Protocol解读</a>
                </p>
            </div>
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/04/16/二叉树/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/20.jpg" class="responsive-img" alt="二叉树">
                        
                        <span class="card-title">二叉树</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">群组欢迎加入群组,闲聊工作&amp;技术&amp;问题等

二叉树的定义&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;二叉树(Binary Tree)是一棵树,其中每个节点都不能有多余两个的</div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-16
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/数据结构与算法/" class="post-category" target="_blank">
                                    数据结构与算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/数据结构/" target="_blank">
                        <span class="chip bg-color">数据结构</span>
                    </a>
                    
                    <a href="/tags/算法/" target="_blank">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/Swift/" target="_blank">
                        <span class="chip bg-color">Swift</span>
                    </a>
                    
                    <a href="/tags/二叉树/" target="_blank">
                        <span class="chip bg-color">二叉树</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/15/Class解读/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/16.jpg" class="responsive-img" alt="Class解读">
                        
                        <span class="card-title">Class解读</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">群组欢迎加入群组,闲聊工作&amp;技术&amp;问题等

类的声明首先我们在runtime.h文件中看到objc_class的结构声明:

/// 类的声明结构

struct objc_class {

Class _Nonnull i</div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-15
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                    Runtime源码解读
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Runtime/" target="_blank">
                        <span class="chip bg-color">Runtime</span>
                    </a>
                    
                    <a href="/tags/底层/" target="_blank">
                        <span class="chip bg-color">底层</span>
                    </a>
                    
                    <a href="/tags/源码/" target="_blank">
                        <span class="chip bg-color">源码</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: waitwalker<br />'
            + '作者: waitwalker<br />'
            + '链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站在原作者&copy;<a href="https://blinkfox.github.io/" target="_blank">Blinkfox</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题基础上搭建.

            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis"><!---->
<a href="https://github.com/waitwalker" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
    <i class="fa fa-github"></i>
</a>

<a href="https://twitter.com/284485487" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-twitter"></i>
</a>

<a href="https://www.facebook.com/profile.php?id=100003684945279" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-facebook"></i>
</a>

<a href="https://t.me/joinchat/Ej0o0A1ntlq5ZFIMzzO5Pw" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-telegram"></i>
</a>

<a href="https://www.weibo.com/1789419613/profile?topnav=1&wvr=6&is_all=1" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-weibo"></i>
</a>


<!--原来-->
<!---->
    <!--<a href="mailto:waitwalker@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-envelope-open"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=284485487" class="tooltipped" data-tooltip="QQ联系我: 284485487" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-qq"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-rss"></i>-->
    <!--</a>-->
<!----></div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->




    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>